'''
    该源码用于将音乐卡点的合成视频转换成720*1280的视频
    旁边视频内容为1920*1080的视频的中间部分
'''
import random
import httpx
import os
from moviepy.editor import *
from src.Snowflake import SnowflakeIDGenerator
from decimal import Decimal
import cv2
import subprocess
import numpy as np
import main_repaire_video


def my_round(num, decimals=0):
    multiplier = 10 ** decimals
    return int(num * multiplier + 0.5) / multiplier


# 定义一个函数来生成视频帧
def make_frame(t):
    # 创建一个空白画布，分辨率为720x1280
    frame = np.zeros((720, 1280, 3), dtype=np.uint8)
    return frame


def make_frame2(t):
    # 创建一个空白画布，分辨率为720x1280
    frame = np.zeros((720, 960, 3), dtype=np.uint8)
    return frame


# 定义一个函数来对视频的每一帧进行模糊处理
def blur_frame(frame):
    blurred_frame = cv2.GaussianBlur(frame, (35, 35), 0)  # 使用高斯模糊进行模糊处理
    return blurred_frame


def create_directory_if_not_exists(file_path):
    directory = os.path.dirname(file_path)

    # 检查文件夹是否存在，如果不存在则创建
    if not os.path.exists(directory):
        os.makedirs(directory)


def read_and_split_file(file_path):
    # 打开文件并读取每一行
    with open(file_path, 'r') as file:
        lines = file.readlines()
    # 分割每一行并组成数组
    return [Decimal(line.strip()) for line in lines]


def read_beat_to_duration(beatArray):
    last_beat = Decimal('0')
    i = 0
    duration = []
    while i < len(beatArray):
        duration.append(float(beatArray[i] - last_beat))
        last_beat = beatArray[i]
        i += 1
    return duration


class VideoConcatenator:
    def __init__(self, video_files):
        self.video_files = video_files
        self.video_clips = []
        self.cover_video_1280_720_background = VideoClip(make_frame2, duration=0.001)
        self.cover_video_1280_720_left = None
        self.cover_video_1280_720_center = None
        self.cover_video_1280_720_right = None

    def setCoverClip(self, clip):
        if not self.cover_video_1280_720_left:
            last_frame_clip = clip.to_ImageClip(t=clip.duration - 0.1, duration=0.001).fx(vfx.resize, height=720)
            self.cover_video_1280_720_left = last_frame_clip \
                .crop(x1=28, y1=0, x2=last_frame_clip.w - 56,
                      y2=last_frame_clip.h) \
                .set_position(('left'))
            return
        if not self.cover_video_1280_720_center:
            last_frame_clip = clip.to_ImageClip(t=clip.duration - 0.1, duration=0.001).fx(vfx.resize, height=720)
            self.cover_video_1280_720_center = last_frame_clip \
                .crop(x1=28, y1=0, x2=last_frame_clip.w - 56,
                      y2=last_frame_clip.h) \
                .set_position(('center'))
            return
        if not self.cover_video_1280_720_right:
            last_frame_clip = clip.to_ImageClip(t=clip.duration - 0.1, duration=0.001).fx(vfx.resize, height=720)
            print(last_frame_clip.w)
            self.cover_video_1280_720_right = last_frame_clip \
                    .crop(x1=28, y1=0, x2=last_frame_clip.w - 56,
                      y2=last_frame_clip.h) \
                .set_position(('right'))
            return

    @property
    def concatenate_videos(self):
        for file in self.video_files:
            clip = VideoFileClip(file, target_resolution=[1920, 1080])
            # 封面
            self.setCoverClip(clip)
            # 转场特效
            transitions = ['fadein', 'fadeout']
            transition_effect = random.choice(transitions)
            clip_final_video = getattr(clip, transition_effect)(0.2)
            # 背景为1920*1080的中间部分加层模糊滤镜
            # video_1280_720 = clip_final_video\
            #     .crop(x1=0, y1=clip_final_video.w, x2=1280, y2=clip_final_video.w-600-720)\
            #     .resize((1280, 720))\
            #     .fl_image(blur_frame)\
            #     .fl_image(blur_frame)\
            #     .fl_image(blur_frame)

            # 背景为黑色
            video_1280_720 = VideoClip(make_frame, duration=clip_final_video.duration)

            # 左中右三部分均设置宽为427占满全屏
            mid_video = clip_final_video.fx(vfx.resize, width=427)
            left_video = clip_final_video.fx(vfx.resize, width=427)
            rigght_video = clip_final_video.fx(vfx.resize, width=427)
            clip_final_video = CompositeVideoClip([video_1280_720.set_duration(video_1280_720.duration),
                                                   mid_video.set_position(("center")),
                                                   left_video.set_position(('left')),
                                                   rigght_video.set_position(('right'))
                                                   ])
            self.video_clips.append(clip_final_video)
        final_clip = concatenate_videoclips(self.video_clips, method="compose")
        return final_clip

    def write_output(self, output_file, add_vfx=None):
        final_clip = self.concatenate_videos
        final_clip = concatenate_videoclips([CompositeVideoClip([self.cover_video_1280_720_background,
                                                                 self.cover_video_1280_720_left,
                                                                 self.cover_video_1280_720_center,
                                                                 self.cover_video_1280_720_right]).fx(vfx.resize,1, 960, 720), final_clip],
                                            method="compose")
        # final_clip = CompositeVideoClip([self.cover_video_1280_720_background,
        #                                  self.cover_video_1280_720_left,
        #                                  self.cover_video_1280_720_center,
        #                                  self.cover_video_1280_720_right])
        if add_vfx:
            for name in add_vfx:
                final_clip = final_clip.fx(name)
        final_clip.write_videofile(output_file, codec="libx264", audio_codec="aac", preset="ultrafast", fps=final_clip.fps,
                                   threads=10)

if __name__ == "__main__":
    # 转义用户输入的字符串
    param = "原神_神里绫华"
    repaired_output_dir = f"outputRepaired"

    # 生成的文件名称
    out_put = f"output\\{SnowflakeIDGenerator().generate_id()}.mp4"
    # url = "http://127.0.0.1:48080/app-api/douyinFileInfo/select/collect/random/single/works"
    # url = "http://127.0.0.1:48080/app-api/douyinFileInfo/select/collect/findAll/collect"
    # url = "https://ppru.cn/api/douyinFileInfo/select/collect/random/single/works"
    url = "https://ppru.cn/api/douyinFileInfo/select/collect/findAll/collect"
    videoPathPrefix = "G:\\clip"
    # 修复视频的bat脚本位置
    repair_video_bat_path = "F:\\Software\CodeFormerGUI\\"
    # repair_video_bat_path = "D:\\software\\codeFormer-GUI\\"
    # 高清修复后的输出路径
    repaired_video_output_dir = f"outputRepaired"
    # 音频保存位置
    music_dir = 'music'

    # 合成视频
    r = httpx.post(url=url, json={"tag": param})
    results = r.json()['data']
    # 替换以下信息为你的视频文件路径和时长
    # video_paths = random.sample([videoPathPrefix + result['path'] for result in results], 5)
    video_paths = [videoPathPrefix + result['path'] for result in results]
    # merged_videos = random.sample(video_paths, 6)
    merged_videos = video_paths
    for index in range(len(merged_videos)):
        merged_videos[index] = main_repaire_video.repaired_video(merged_videos[index], repaired_video_output_dir,
                                                                 music_dir, repair_video_bat_path)
    concatenator = VideoConcatenator(merged_videos)
    create_directory_if_not_exists(out_put)
    concatenator.write_output(out_put, add_vfx=[vfx.mirror_x])
